from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse, path
from django.utils.safestring import mark_safe
from django.db import models
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from .models import Code, CodeVersion
import html
import json

class CodeVersionInline(admin.TabularInline):
    model = CodeVersion
    extra = 0
    readonly_fields = ('version_number', 'created_at', 'file_size', 'get_enhanced_content_preview')
    fields = ('version_number', 'get_enhanced_content_preview', 'commit_message', 'created_at', 'file_size')
    
    class Media:
        css = {
            'all': ('admin/css/code_highlight.css',)
        }
        js = ('admin/js/code_highlight.js',)
    
    def get_enhanced_content_preview(self, obj):
        """增强的代码内容预览，支持语法高亮"""
        if obj.content:
            preview = obj.content[:300] + '...' if len(obj.content) > 300 else obj.content
            escaped_content = html.escape(preview)
            language = obj.code.language.lower() if obj.code.language else 'python'
            
            return format_html(
                '<div class="code-preview-container">' +
                '<div class="code-preview-toolbar">' +
                '<div class="code-preview-language">{}</div>' +
                '<div class="code-preview-actions">' +
                '<a href="#" class="code-preview-btn" onclick="showVersionDiff({}, {})">对比差异</a>' +
                '</div>' +
                '</div>' +
                '<div class="code-highlight {}" data-language="{}">{}</div>' +
                '</div>',
                language.upper(),
                obj.version_number,
                obj.version_number - 1 if obj.version_number > 1 else obj.version_number,
                language,
                language,
                escaped_content
            )
        return '无内容'
    get_enhanced_content_preview.short_description = '代码预览'

@admin.register(Code)
class CodeAdmin(admin.ModelAdmin):
    list_display = ('title', 'user', 'language', 'created_at', 'updated_at', 'is_active', 'get_version_count', 'get_battle_usage')
    list_filter = ('language', 'is_active', 'created_at', 'user')
    search_fields = ('title', 'description', 'user__username')
    readonly_fields = ('created_at', 'updated_at', 'get_enhanced_latest_preview', 'get_usage_stats', 'get_version_history')
    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'title', 'description', 'language', 'is_active')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
        ('代码预览', {
            'fields': ('get_enhanced_latest_preview',),
            'classes': ('wide',)
        }),
        ('版本历史', {
            'fields': ('get_version_history',),
            'classes': ('wide',)
        }),
        ('使用统计', {
            'fields': ('get_usage_stats',),
            'classes': ('collapse',)
        }),
    )
    inlines = [CodeVersionInline]
    actions = ['activate_codes', 'deactivate_codes']
    
    class Media:
        css = {
            'all': ('admin/css/code_highlight.css',)
        }
        js = ('admin/js/code_highlight.js',)
    
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('version-diff/<int:code_id>/<int:version1>/<int:version2>/', 
                 self.admin_site.admin_view(self.version_diff_view), 
                 name='code_version_diff'),
            path('version-content/<int:version_id>/', 
                 self.admin_site.admin_view(self.version_content_view), 
                 name='code_version_content'),
        ]
        return custom_urls + urls
    
    def version_diff_view(self, request, code_id, version1, version2):
        """代码版本差异对比视图"""
        code = get_object_or_404(Code, id=code_id)
        v1 = get_object_or_404(CodeVersion, code=code, version_number=version1)
        v2 = get_object_or_404(CodeVersion, code=code, version_number=version2)
        
        return JsonResponse({
            'success': True,
            'version1': {
                'number': v1.version_number,
                'content': v1.content or '',
                'created_at': v1.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'commit_message': v1.commit_message or ''
            },
            'version2': {
                'number': v2.version_number,
                'content': v2.content or '',
                'created_at': v2.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'commit_message': v2.commit_message or ''
            },
            'language': code.language
        })
    
    def version_content_view(self, request, version_id):
        """获取版本内容视图"""
        version = get_object_or_404(CodeVersion, id=version_id)
        
        return JsonResponse({
            'success': True,
            'content': version.content or '',
            'version_number': version.version_number,
            'language': version.code.language,
            'created_at': version.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'commit_message': version.commit_message or ''
        })

    def get_version_count(self, obj):
        return obj.get_version_count()
    get_version_count.short_description = '版本数量'
    
    def get_battle_usage(self, obj):
        """获取代码在对战中的使用次数"""
        try:
            from battles.models import Battle
            count = Battle.objects.filter(
                models.Q(player1_code=obj) | models.Q(player2_code=obj)
            ).count()
            return count
        except:
            return 0
    get_battle_usage.short_description = '对战使用次数'
    
    def get_enhanced_latest_preview(self, obj):
        """增强的最新版本代码预览，支持语法高亮"""
        latest_version = obj.versions.first()
        if latest_version and latest_version.content:
            preview = latest_version.content[:600] + '...' if len(latest_version.content) > 600 else latest_version.content
            escaped_content = html.escape(preview)
            language = obj.language.lower() if obj.language else 'python'
            
            return format_html(
                '<div class="code-preview-container">' +
                '<div class="code-preview-toolbar">' +
                '<div class="code-preview-language">{} - 版本 {}</div>' +
                '<div class="code-preview-actions">' +
                '<button class="code-preview-btn" onclick="copyCode(this)">复制代码</button>' +
                '<button class="code-preview-btn" onclick="toggleFullscreen(this)">全屏查看</button>' +
                '</div>' +
                '</div>' +
                '<div class="code-highlight {}" data-language="{}">{}</div>' +
                '</div>',
                language.upper(),
                latest_version.version_number,
                language,
                language,
                escaped_content
            )
        return '无代码内容'
    get_enhanced_latest_preview.short_description = '最新代码预览'
    
    def get_version_history(self, obj):
        """版本历史展示"""
        versions = obj.versions.all()[:10]  # 显示最近10个版本
        if not versions:
            return '暂无版本历史'
        
        html_parts = ['<div class="code-version-history">']
        
        for i, version in enumerate(versions):
            html_parts.append('<div class="code-version-item">')
            html_parts.append('<div class="code-version-header">')
            html_parts.append(f'<div class="code-version-info">版本 {version.version_number}</div>')
            html_parts.append(f'<div class="code-version-date">{version.created_at.strftime("%Y-%m-%d %H:%M:%S")}</div>')
            html_parts.append('</div>')
            
            if version.commit_message:
                html_parts.append(f'<div class="code-version-message">{html.escape(version.commit_message)}</div>')
            
            html_parts.append('<div class="code-version-stats">')
            html_parts.append(f'文件大小: {version.file_size or 0} 字节')
            
            if i < len(versions) - 1:  # 不是最后一个版本
                next_version = versions[i + 1]
                html_parts.append(f' | <a href="#" class="code-preview-btn" onclick="showVersionDiff({obj.id}, {version.version_number}, {next_version.version_number})">与上一版本对比</a>')
            
            html_parts.append('</div>')
            html_parts.append('</div>')
        
        html_parts.append('</div>')
        
        return format_html(''.join(html_parts))
    get_version_history.short_description = '版本历史'
    
    def get_usage_stats(self, obj):
        """使用统计信息"""
        try:
            from battles.models import Battle
            total_battles = Battle.objects.filter(
                models.Q(player1_code=obj) | models.Q(player2_code=obj)
            ).count()
            
            win_battles = Battle.objects.filter(
                models.Q(player1_code=obj, result='player1_win') | 
                models.Q(player2_code=obj, result='player2_win')
            ).count()
            
            win_rate = (win_battles / total_battles * 100) if total_battles > 0 else 0
            
            return format_html(
                '<div style="padding: 10px; background: #e9ecef; border-radius: 4px;">'
                '<strong>总对战次数:</strong> {}<br>'
                '<strong>胜利次数:</strong> {}<br>'
                '<strong>胜率:</strong> {:.1f}%<br>'
                '<strong>版本数量:</strong> {}'
                '</div>',
                total_battles, win_battles, win_rate, obj.get_version_count()
            )
        except:
            return '统计信息暂不可用'
    get_usage_stats.short_description = '使用统计'
    
    def activate_codes(self, request, queryset):
        """批量激活代码"""
        updated = queryset.update(is_active=True)
        self.message_user(request, f'成功激活 {updated} 个代码。')
    activate_codes.short_description = '激活选中的代码'
    
    def deactivate_codes(self, request, queryset):
        """批量停用代码"""
        updated = queryset.update(is_active=False)
        self.message_user(request, f'成功停用 {updated} 个代码。')
    deactivate_codes.short_description = '停用选中的代码'

@admin.register(CodeVersion)
class CodeVersionAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'version_number', 'created_at', 'file_size', 'get_language')
    list_filter = ('created_at', 'code__language', 'code__user')
    search_fields = ('code__title', 'commit_message', 'code__user__username')
    readonly_fields = ('version_number', 'created_at', 'file_size', 'get_content_display')
    fieldsets = (
        ('版本信息', {
            'fields': ('code', 'version_number', 'commit_message', 'created_at', 'file_size')
        }),
        ('代码内容', {
            'fields': ('get_content_display',),
            'classes': ('wide',)
        }),
    )
    
    def get_language(self, obj):
        return obj.code.language
    get_language.short_description = '编程语言'
    
    def get_content_display(self, obj):
        """格式化显示代码内容"""
        if obj.content:
            escaped_content = html.escape(obj.content)
            return format_html(
                '<div style="background: #f8f9fa; padding: 15px; border-radius: 4px; font-family: \'Courier New\', monospace; white-space: pre-wrap; max-height: 400px; overflow-y: auto; border: 1px solid #dee2e6;">{}</div>',
                escaped_content
            )
        return '无内容'
    get_content_display.short_description = '代码内容'